using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Shop.Model;
using Shop.Framework.Keys;
using Shop.Framework.Services;
using Shop.Model.Custom;
using Shop.Framework.Runtime;

namespace Shop.Website.Controllers {
    public class CartController : Controller {
        //
        // GET: /Cart/

        public ActionResult Index() {
            return View();
        }

        public string AddToCart(int idProduct, int quantity) {
            try {
                List<OrderItem> orderList = WebCart.Self.OrderItem;
                if (orderList == null) {
                    orderList = new List<OrderItem>();
                    WebCart.Self.OrderItem = orderList;
                }


                var duplicate = WebCart.Self.OrderItem.FirstOrDefault(x => x.IdProduct == idProduct);

                if (duplicate == null) {
                    OrderItem item = (new ProductService()).CreateCartItem(idProduct, quantity);
                    WebCart.Self.OrderItem.Add(item);
                } else
                    duplicate.Quantity += quantity;

            } catch (Exception ex) {
                throw ex;
            }
            return "added";
        }

        public ActionResult AddToCart2() {
            try {
                int quantity = 1;
                int idProduct = Convert.ToInt32(Request["idProduct"]);
                List<OrderItem> orderList = WebCart.Self.OrderItem;
                if (orderList == null) {
                    orderList = new List<OrderItem>();
                    WebCart.Self.OrderItem = orderList;
                }


                var duplicate = WebCart.Self.OrderItem.FirstOrDefault(x => x.IdProduct == idProduct);

                if (duplicate == null) {
                    OrderItem item = (new ProductService()).CreateCartItem(idProduct, quantity);
                    WebCart.Self.OrderItem.Add(item);
                } else
                    duplicate.Quantity += quantity;

            } catch (Exception ex) {
                throw ex;
            }
            return Redirect(Request.UrlReferrer.ToString());
        }


        public ActionResult Items() {
            return View();
        }

        public ActionResult Delete(int idProduct, int quantity) {

            if (Request.Form["delete"] != null) {
                var match = WebCart.Self.OrderItem.FirstOrDefault(x => x.IdProduct == idProduct);
                if (match != null)
                    WebCart.Self.OrderItem.Remove(match);
            } else {
                var match = WebCart.Self.OrderItem.FirstOrDefault(x => x.IdProduct == idProduct);
                match.Quantity = quantity;
            }
            return RedirectToAction("Items");
        }

        [PaymentFilter]
        public ActionResult Checkout() {
            Session["FromCheckout"] = null;
            return View();
        }

        [PaymentFilter]
        public ActionResult Reciept() {

            try {
                Customer cust = WebCart.Self.CurrentCustomer;

                WebCart.Self.CustomerOrder = new CustomerOrder {
                    Customer = WebCart.Self.CurrentCustomer,
                    DateOrdered = DateTime.Now,
                    DeliveryCity = Request["DeliveryCity"],
                    DeliveryCountry = Request["DeliveryCountry"],
                    DeliveryStreet = Request["DeliveryCity"],
                    DeliveryZip = Request["DeliveryCity"],
                    FirstName = Request["FirstName"],
                    LastName = Request["LastName"]
                };

                CustomerOrder order = WebCart.Self.CustomerOrder;

                //Validate Zip
                int zip = 0;
                if (!int.TryParse(Request["DeliveryZip"], out zip)) {
                    Session["ErrorMessage"] = "Invalid zipCode";
                    return RedirectToAction("Checkout");
                }

                if (! (zip >= 1000 && zip <= 9807)) {
                    Session["ErrorMessage"] = "Invalid zipCode, not a valid \"Philippine\" zipcode..";
                    return RedirectToAction("Checkout");
                }

                //Delivery
                order.ExtraChargeDescription = Request["ExtraChargeDescription"];
                if (order.ExtraChargeDescription == "Pick-up") {
                    order.ExtraCharge = 0;
                    order.ForPickUp = true;
                    order.CreditCardNumber = string.Empty;
                    order.Completed = false;
                } else
                    order.ExtraCharge = 800.00m;

                order.PaymentType = Request["PaymentType"];
                if (order.PaymentType == "CreditCard") {
                    order.CardType = Request["CardType"];
                    order.CreditCardNumber = Request["CreditCardNumber"];

                    var x = CCVerifier.Self.CheckCC(order.CreditCardNumber);
                    if (!x.CardValid) {
                        Session["ErrorMessage"] = "Invalid credit card number...";
                        return RedirectToAction("Checkout");
                    }

                } else {
                    order.CreditCardNumber = string.Empty;
                    order.CardType = string.Empty;
                }

                decimal totalPayment = 0;
                int itemsOrdered = 0;
                WebCart.Self.OrderItem.ForEach(delegate(OrderItem item) {
                    totalPayment += item.Quantity * item.TaxedPrice;
                    itemsOrdered += item.Quantity;
                });

                order.TotalPrice = totalPayment + order.ExtraCharge;
                order.TotalItemsOrdered = itemsOrdered;
                order.DeliveryDate = DateTime.Now.AddDays(3);

                CartService service = new CartService();
                bool ok = service.FinishPayment(order);


            } catch (Exception ex) {
                Session["ErrorMessage"] = ex.Message;
                return RedirectToAction("Checkout");
            }
            Session["ErrorMessage"] = null;
            return View();
        }

    }
}
